/**
 *Project: jh-framework
 *File: cn.xkshow.framework.web.filter.EncodingFilter.java 
 *Author: hardy(admin@xkshow.cn) Copyright
 ****************************************************************
 *   VERSION       DATE            BY       CHANGE/COMMENT
 * --------------------------------------------------------------
 *    1.0        2013-7-4         hardy         create
 ****************************************************************
 *note:
 ***************************************************************/
package cn.xkshow.framework.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;

public class EncodingFilter implements Filter {
	protected boolean enable;
	protected FilterConfig filterConfig;
	protected String targetEncoding = "UTF-8";

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;

		loadConfigParams();
	}

	private void loadConfigParams() {
		this.targetEncoding = this.filterConfig.getInitParameter("encoding");

		String strIgnoreFlag = this.filterConfig.getInitParameter("enable");
		if (strIgnoreFlag.equalsIgnoreCase("true")) {
			this.enable = true;
		} else {
			this.enable = false;
		}
	}

	public void destroy() {
		this.filterConfig = null;
		this.targetEncoding = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (this.enable) {
			request.setCharacterEncoding(this.targetEncoding);
		}

		response.setContentType("text/html; charset=" + this.targetEncoding);

		if (!(request instanceof HttpServletRequest)) {
			chain.doFilter(request, response);
			return;
		}

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		if (httpRequest.isRequestedSessionIdFromURL()) {
			HttpSession session = httpRequest.getSession();
			if (session != null) {
				session.invalidate();
			}

		}

		HttpServletResponseWrapper wrappedResponse = new HttpServletResponseWrapper(
				httpResponse) {
			public String encodeRedirectUrl(String url) {
				return url;
			}

			public String encodeRedirectURL(String url) {
				return url;
			}

			public String encodeUrl(String url) {
				return url;
			}

			public String encodeURL(String url) {
				return url;
			}
		};
		chain.doFilter(request, wrappedResponse);
	}
}
